
////// window with list of modules

var modModules = new Class({
	Extends:boxWindow,
	options: $extend({
		BtnRefresh: false,
		BtnMin: false,
		BtnSettings: false,
		title: lang.label('menu_title'),
		name: 'modModules',
		uniqueCss: true,
		modal: true,
		BtnClose: true,
		fixed: true,
		left:0,
		top:0,
		width:760,
		isBox:false,
		category:false
	}, custom_options.AddWidgetWindow||{}),

	initPageNumber:0,
	currentPageNumber:1,
	TotalPageNumber:1,					  
	widgetCategory: null,
	isNeedUpdate:false,
	currentTime:0,
	PackageManager:null,
	update_info:null,
    categoryPrefix  : 'category_',
    selectedCategory: 'all',

	///// get where to display the box
	initialize: function(eid){
		if($defined( $('canvas' + wfc_mainScreen.currActive) ) == false) 
		{
			wfc_error_msg(lang.label("msg_addatleastonetab"));
			return false;
		} 
		this.parent();
		this.currentTime=new Date().getTime();
		this.widgetCategory = new CCategory(this.currentTime);
		if (!this.options.category)
			this.widgetCategory.switchCat('all');
        
        this.fillTitle(this.options.title );
		tempAdded=[];
		this.TotalPageNumber=Math.ceil(this.widgetCategory.get().length/addWidgetsPerPage);
		this.PackageManager=new TM_WidgetPackageManager();
 		if(this.PackageManager.getNeedUpdate())
		{
			this.isNeedUpdate=true;
		}
	}, 

	IsChecked:function(id){
		var output=0;
		if($defined(tempAdded[id]) && tempAdded[id]!=0)
		output=1;
		return output;
	},	

	SwitchCategory:function(el){
        var szCategory = $(el).getAttribute('id').replace(this.categoryPrefix,'');
        this.selectedCategory = szCategory;
        this.widgetCategory.switchCat(szCategory);
		this.TotalPageNumber = Math.ceil(this.widgetCategory.get().length/addWidgetsPerPage);
		this.currentPageNumber = 1;
		this.initPageNumber = addWidgetsPerPage*(this.currentPageNumber-1);
		tempAdded.empty();
		this.onFinish();
	},

	UpdateCallBack:function(myJSON){
		 this.update_info.setStyle('display','none');
		 if(myJSON.response.json.errcode==0)
		 {
		 	if(myJSON.response.json.result['Status']==0)
		 	{
		 		var answer = confirm(lang.labelText("update_reload"));
     		if (answer)
      		window.location.reload();
      }
      else
      	wfc_error_msg( lang.label('no_need_update') );
     }
     else
     {
     		wfc_error_msg(lang.label("errorcode_"+myJSON.response.json.errcode));
     }
	},
	/////// load the info in the box
	onFinish: function(){
		//this.fillTitle(this.options.title); 
		$('modal_content').setHTML(""); 
		var mainobj = this;
		var divMain =null;
		var str ="";
		var addText = lang.label("menu_add2");
		var div2;
		var nm ="";
		var ds ="";
    var img ="";
    var cat ="";
    var lastupdate ="";
		var posx = (getWidth()/2 )-(this.options.width/2);
		var posy = (getHeight()/2)-(this.options.height/2);
		var overLay = $('modaloverlay');
                var scroll = $(document.body).getScroll().y;
		var modCss = this.options.uniqueCss ? this.options.name : '';
		var CatWidgetList = this.widgetCategory.get();
        var content_obj = $(mainobj.contentid);

		if(this.options.isBox){
			overLay.setStyle('width', this.options.width+'px'); 
			overLay.setStyle('height', this.options.height+'px'); 
			overLay.setStyle('top', posy); 
			//overLay.setStyle('left', posx); 
		} else { 
			overLay.setStyle('width', this.options.width+'px');
			overLay.setStyle('top' , (15+scroll)+'px'); 
			//overLay.setStyle('left', posx); 
		}

		var A = new Element("table", {
			"cellspacing": "0",
			"cellpadding": "0",
			"width": "100%"
		}).injectInside($(mainobj.contentid));
		var C = new Element("thead").injectInside(A);
		var D = new Element("tr").injectInside(C);
		if (this.options.category)
		{
			var M = new Element("td", {
				"width": "20%",
				"style":"vertical-align:top"
			}).injectInside(D);
			var N = new Element("td", {
				"width": "80%"
			}).injectAfter(M);
		}
		else
		{
			var M = new Element("td", {
				"width": "100%"
			}).injectInside(D);
			var N=M;
		}
        this.widgetBox = N;
		var B = new Element("tbody").injectAfter(C);

		if (this.options.category) {
			// remove this
            //var E=new Element('div', {'id':'category'}).injectInside(M).setHTML(lang.label("category"));
            
            // The parent
            var O = new Element('ul', {'id':'posts'}).injectInside(M);
            
            // category: latest widgets
			if($chk(this.widgetCategory.arrCategory["latest"]))
			{
				var li = new Element('li').injectInside(O);
                var cid = this.categoryPrefix + 'latest';
				var link = new Element('a', {'id':cid}).injectInside(li);
				link.setText(lang.label("latest_widgets"));
				link.addEvent('click', function(event){
					this.SwitchCategory(event.target);
				}.bind(this));
			}
            
            // category: all widgets
            var li = new Element('li').injectInside(O);
            var cid = this.categoryPrefix+'all';
            var all_wid = new Element('a', {'id':cid}).injectInside(li);
			all_wid.setText(lang.label("all_widgets"));
			all_wid.addEvent('click', function(event){
				this.SwitchCategory(event.target);
			}.bind(this));
			
			// add all widget categories 
			this.widgetCategory.arrCatList.each(function(el, i){
				if(el!="latest")
				{
					var li = new Element('li').injectInside(O);
                    var cid = this.categoryPrefix + el;
					var link = new Element('a', {'id':cid}).injectInside(li);
					link.setText(lang.labelText('category_'+el));
					link.addEvent('click', function(event){
						this.SwitchCategory(event.target);
					}.bind(this));
				}
			}, this);
            
            // highlight selected category
            this.MarkCategory();
		}
		 		
   if(this.isNeedUpdate) {
   	this.update_info = new Element('div').injectInside(N).setStyle('padding-bottom','8px');
   }       
    
    this.MakePagination(N);
    
    var item_wrap = new Element('div', {'class': 'wrap_item'}).injectInside(N);
        
		for(var id=this.initPageNumber;id<CatWidgetList.length;id++)
		{
			if(id>=(addWidgetsPerPage*this.currentPageNumber))
				break;
			var obj=CatWidgetList[id];  
			if(obj!=undefined) {
				divMain = new Element('div', {'class': 'widget_item', 'id': 'fixedsub_'+ id});
                
                // if have category
				if (!this.options.category) {
			  	  divMain.setStyle("width","735px");
                }
				
				
        
                // get widget display name                
                var widget_lang = window[obj.name+'_locLang'];
                if(!widget_lang) {
                    window[obj.name+'_locLang'] = new localLang(obj.name);
                    modList.set(obj.name, window[obj.name+'_locLang'].label('title'));
                    widget_lang = window[obj.name+'_locLang'];
                }

                nm = widget_lang.label('title');        

                // get icon
                var _strWidgetDir;
                if (obj.userGenerated == 1){
                    _strWidgetDir = USER_GENERATED_WIDGET_DIR;
                }else{
                    _strWidgetDir = modFolder;
                }
                img = obj.big_icon ? '<img src="'+ _strWidgetDir + "/" + obj.name + "/img/" + obj.big_icon +'" />':'';
                
                // get widget description
				var ds_label  = widget_lang.label('description');                
                ds = img +'<p>'+ ds_label +'</p>';
                                cat="";
				var categoryarray=(obj.category).split(",");
				var categoryarraylength=categoryarray.length;
				if(categoryarraylength==1)
					cat = lang.label('category_'+categoryarray[0]);	
				else
				{
					for(var index=0;index<categoryarraylength;index++)
					{
							var temp=index+1;
							if(categoryarraylength==temp)
								cat = cat + lang.label('category_'+categoryarray[index]);
							else
								cat = cat + lang.label('category_'+categoryarray[index])+ ',';
					};
				}
				lastupdate=(obj.lastupdate.toInt()==0)?"":new Date(obj.lastupdate.toInt()).formatDate(lang.label("lastupdate_format"));
				//str += " <td width='80%' valign='top'> <span class='modName'>"+ nm +"</span><br> <span class='modDesc'>"+ ds +"</span></td> </tr> ";
				var checkbox ='<input type="checkbox" name="wid_chk[]" class="wid_chk_'+id+'" '+' id="wid_chk_'+id+'"   />';
				str = '<tr class="widget_title"><th width="25">'+ checkbox +'</th><td width="99%"><label for="wid_chk_'+id+'">'+ nm +'</label>';
				var difference=(this.currentTime-obj.lastupdate.toInt()) - (86400 * wfc_shownew_days* 1000);
				if(difference <0)
				{
					//alert(new Date().getTime()-obj.lastupdate.toInt());
					str+='&nbsp;<span id="newdisplay" style="color:red;">'+lang.label("newwidget")+'</span>';
				}
				str+='</td></tr>';
				str+= '<tr class="widget_desc"><td colspan="2">'+ ds +'</td></tr>';
			    str+= '<tr class="widget_cat"><td colspan="2">'+lang.label("category_widget")+ cat +'</td></tr>';
				str+= '<tr class="widget_lastupdate"><td colspan="2">'+lang.label("lastupdate_at")+ lastupdate +'</td></tr>';
				//div2.setHTML("<br /><table border='0' class='widgetsBox'>"+ str +"</table>"); 
				divMain.setHTML('<table border="0" cellspacing="0" cellpadding="0" class="widgetsBox">'+ str +'</table>');
				if($chk($(divMain).getElement(".wid_chk_"+id)))
				{ 
					$($(divMain).getElement(".wid_chk_"+id)).removeEvents('click');
					$($(divMain).getElement(".wid_chk_"+id)).addEvent('click', function(event){
						var checkboxid=event.target.id;
						var widgetid=event.target.id.split("_")[2].toInt();
						//alert(widgetid+" "+CatWidgetList[widgetid].name);
						addWidgets(widgetid, CatWidgetList[widgetid].name);
					});
				}
				divMain.injectInside(item_wrap);
				if(this.IsChecked(id)==1)
					$('wid_chk_'+id).checked=true;
				else
					$('wid_chk_'+id).checked=false;
				showModules=true;
			}
		}  
		$(item_wrap).setStyle('min-height','370px');
        
        this.MakePagination(N);
        
        if(this.isNeedUpdate) {
            var update_text = new Element('span').setHTML(lang.label("new_widgets_avail"))
                                                 .setStyle('padding-right','8px')
                                                 .injectInside(this.update_info);
            var update_btn = new Element('input',{type:'button', id:'widget_update_btn', value:lang.labelText("update")}).injectInside(this.update_info).addEvent('click', function(){ 
                update_text.setStyle('display','none');
                update_btn.setStyle('display','none');
                this.update_info.setHTML('<div class="on_loading">'+lang.label("updating_widgets")+'</div>');
                this.PackageManager.update.bind(this)(this.UpdateCallBack);
            }.bind(this));
        }

		$('overlay').setStyle('height', getScrollHeight()+"px"); 
	},
    
    MarkCategory: function()
    {
        var el = $(this.categoryPrefix+this.selectedCategory); 
        var lis = $('posts').getElements('li');
        var i = lis.length;
        while(i--) {
            var li = lis[i];
            if(li.hasClass('selected')) {
                li.removeClass('selected');
            }
        }
        var sel = el.getParent('li')
        sel.addClass('selected');
    },
    
    MakePagination: function(parent) 
    {
		var N = parent ? parent : this.widgetBox;
        var diva = new Element('div', {'class' : 'widget_content fixedsubClose'}).injectInside(N); 

		var changePage=new Element('div', {'class' : 'fixedsubChange'}).injectInside(diva);
		changePage.setHTML(
			'<table style="height:18px;" cellspacing="0" cellpadding="0" border="0" align="center">'+
      			'<tr>'+
        		'<td nowrap="nowrap"><a href="javascript:void(0);"><img class="submit_begin" src="img/default/pagination-beginning.gif" title="'+lang.label('firstpage')+'" /></a></td>'+
        		'<td nowrap="nowrap"><img width="4" src="img/default/1space.gif"/></td>'+
       			'<td nowrap="nowrap"><a href="javascript:void(0);"><img class="submit_prev" title="'+lang.label('previouspage')+'" src="img/default/pagination-previous.gif"/></a></td>'+
        		'<td nowrap="nowrap"><img width="7" src="img/default/1space.gif"/></td>'+
        		'<td style="font-size:11px;" nowrap="nowrap">&nbsp;'+lang.label('page')+' '+this.currentPageNumber+'&nbsp; '+lang.label('of')+' &nbsp;'+this.TotalPageNumber+'</td>'+
        		'<td nowrap="nowrap"><img width="7" src="img/default/1space.gif"/></td>'+
       			'<td nowrap="nowrap"><a href="javascript:void(0);"><img class="submit_next" title="'+lang.label('nextpage')+'" src="img/default/pagination-next.gif"/></a></td>'+
       			'<td nowrap="nowrap"><img width="4" height="1" src="img/default/1space.gif"/></td>'+
        		'<td nowrap="nowrap"><a href="javascript:void(0);"><img class="submit_end" title="'+lang.label('lastpage')+'" src="img/default/pagination-end.gif"/></a></td>'+
       			'<td nowrap="nowrap"><img width="4" height="1" src="img/default/1space.gif"/></td>'+
     			'</tr>'+
    			'</table>'
		);

		// Save button
		var pagesave = new Element('input',{'events':{'click':this.SaveWidget.bind(this)},'id':'reloadButton',  'type':'button', 'value':lang.label('btn_reload')} ).injectInside(diva); 

		// Cancel button
		var pageclose = new Element('input', {'events':{'click':function(event){ var event = new Event(event); this.closeModal(); }.bind(this)}, 'type':'button', 'value':lang.label('btn_cancel')}).injectInside(diva);

		changePage.getElement("img.submit_end").addEvent('click',function(){
			this.currentPageNumber=this.TotalPageNumber;
			this.initPageNumber=addWidgetsPerPage*(this.currentPageNumber-1);
				this.onFinish();
		}.bind(this));

		changePage.getElement("img.submit_begin").addEvent('click',function(){
			this.currentPageNumber=1;
			this.initPageNumber=addWidgetsPerPage*(this.currentPageNumber-1);
			this.onFinish();
		}.bind(this));

		changePage.getElement("img.submit_next").addEvent('click',function(){
			this.currentPageNumber=this.currentPageNumber+1;
			if(this.currentPageNumber>this.TotalPageNumber)
				this.currentPageNumber=this.TotalPageNumber;
			this.initPageNumber=addWidgetsPerPage*(this.currentPageNumber-1);
			this.onFinish();
		}.bind(this));

		changePage.getElement("img.submit_prev").addEvent('click',function(){
			this.currentPageNumber=this.currentPageNumber-1;
			if(this.currentPageNumber==0)
				this.currentPageNumber=1;
			this.initPageNumber=addWidgetsPerPage*(this.currentPageNumber-1);
			this.onFinish();
		}.bind(this));
        
        
    },
    SaveWidget: function()
    {
        if(tempAdded.length>0) {
            saveWidgets();
            return ;
        } else { //messege_reload
            if(!this.messageBox) {
                this.messageBox =  new Element('div',{'id':'module_add_message'}).inject(this.widgetBox, 'top');
            }
            wfc_error_msg( lang.label('messege_reload'), {addTo: this.messageBox});
            return ;
        }
    }
});

var CCategory = new Class({
	arrCategory: [],
	arrCatList: [],
	CurrentCategory: "",

	initialize: function(currentTime){
		widgetList.widgets.each(function(el, i) {
			var categoryarray=el.category.split(",");
				categoryarray.each(function(cat, j) {
					if (!$chk(this.arrCategory[cat]))
					{
						this.arrCategory[cat] = [];
						this.arrCatList.push(cat);
					}
					this.arrCategory[cat].push(el);
					var difference=(currentTime-el.lastupdate.toInt()) - (86400 * wfc_shownew_days* 1000);
					if(difference <0)
					{
						if (!$chk(this.arrCategory["latest"]))
						{
							this.arrCategory["latest"] = [];
							this.arrCatList.push("latest");
						}
						this.arrCategory["latest"].push(el);
					}
				},this);
				//this.CurrentCategory = this.arrCatList[0];
				this.CurrentCategory = 'all';
		}, this);
	},
	
	get: function(){
		if (this.CurrentCategory == 'all')
			return widgetList.widgets;
		else
			return this.arrCategory[this.CurrentCategory];
	},
	
	switchCat: function(szCategory){
		this.CurrentCategory = szCategory;
	}
});
